package externalBusiness;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import models.MyConfig;
import models.Request;
import models.ReturnJson;
import models.TestServerBusinessImpl;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * Created by yangxianming on 2019/6/4.
 * py脚本调用器，后期可以扩展成对第三方脚本的调用支持
 */
public class PythonExecter implements TestServerBusinessImpl {
    @Override
    public String doIt(HttpServletRequest request, MyConfig myConfig) {
        String pythonPath = myConfig.getPythonPath();
        ReturnJson returnJson = new ReturnJson();
        String requestInfo;
        try {
            requestInfo = Request.getBody(request);
            System.out.println(requestInfo);
        }catch (Exception e){
            //请求流如果出现异常的时候
            returnJson.setApiStatus(0);
            returnJson.setErrorMsg(e.getMessage());
            return returnJson.toString();
        }

        JSONArray taskList = JSON.parseArray(requestInfo);

        if (Objects.equals(myConfig.getNo2Factory(), null)){
            No2Factory no2Factory = new No2Factory();
            no2Factory.setMyConfig(myConfig);
            myConfig.setNo2Factory(no2Factory);
            no2Factory.start();
        }
        No2Factory no2Factory = myConfig.getNo2Factory();
        for (Object o: taskList){
            JSONObject ot = (JSONObject)o;
            JSONObject oneTask = new JSONObject();
            oneTask.put("caseName", ot.getString("caseName"));
            oneTask.put("caseId", ot.getString("caseId"));
            oneTask.put("batchNo", ot.getString("batchNo"));
            no2Factory.inputFactory(oneTask);
        }

        return "";
    }
}
